package apis

import (
	"QImages/entity"
	"QImages/serializer"
	"fmt"
	"log"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type Comment struct {
	UserID   uint   `json:"userId" binding:"required"`
	ImageID  uint   `json:"imageId" binding:"required"`
	ParentID *uint  `json:"parentId"`
	Content  string `json:"content" binding:"required"`
}

// GetComments 获取所有评论
func GetComments(c *gin.Context) {
	results, err := entity.Comments()
	if err != nil {
		c.JSON(http.StatusOK, serializer.Err(serializer.CodeNothingFound, "未找到评论信息", nil))
		return
	}
	var arr []serializer.Comment
	for _, r := range results {
		arr = append(arr, serializer.BuildComment(&r))
	}
	c.JSON(http.StatusOK, serializer.OK("查询成功", arr))
}

// PostComment 插入评论
func PostComment(c *gin.Context) {
	var param Comment
	if err := c.ShouldBindJSON(&param); err != nil {
		log.Println(err.Error())
		c.JSON(http.StatusOK, serializer.ParamErr("参数错误，评论失败", nil))
		fmt.Println(err.Error())
		return
	}
	var dbComment = entity.Comment{
		UserID:   param.UserID,
		ImageID:  param.ImageID,
		ParentID: param.ParentID,
		Content:  param.Content,
	}
	id, err := dbComment.Insert()
	if err != nil {
		c.JSON(http.StatusOK, serializer.DBErr("评论插入失败", nil))
		return
	}
	c.JSON(http.StatusOK, serializer.OK("评论成功", id))
	return
}

// DelCommentById 根据id删除
func DelCommentById(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusOK, serializer.ParamErr("", nil))
		return
	}
	_, err = entity.DeleteComment(uint(id))
	if err != nil {
		c.JSON(http.StatusOK, serializer.ServerErr("删除失败", nil))
		return
	}
	c.JSON(http.StatusOK, serializer.OK("删除成功", nil))
}
